package com.runfast.common.security.spring;

import com.runfast.common.web.shiro.LoginMode;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: lijin
 * @date: 2018年06月01日
 */
public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        AbstractAuthenticationToken authRequest = null;
        LoginMode loginMode = LoginMode.valueOf(request.getParameter("loginMode"));
        String mobile = null;
        switch (loginMode) {
            case mobile_pwd:
                mobile = request.getParameter("mobile");
                String password = request.getParameter("password");
                authRequest = new UsernamePasswordAuthenticationToken(mobile, password, null);
                break;

            case mobile_sms_code:

                mobile = request.getParameter("mobile");
                String smsCode = request.getParameter("smsCode");
                authRequest = new MobileSmsCodeAuthenticationToken(mobile, smsCode, null);
                break;
            case third:
                String thirdLoginId = request.getParameter("thirdLoginId");
                String thirdLoginType = request.getParameter("thirdLoginType");
                authRequest = new ThirdAuthenticationToken(thirdLoginId, thirdLoginType, null);

                break;
        }

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected void setDetails(HttpServletRequest request,
                              AbstractAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}
